#include "servicemanager.h"

#include <qbluetoothdeviceinfo.h>
#include <qbluetoothaddress.h>

static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c8");

QTM_USE_NAMESPACE

ServiceManager::ServiceManager() : m_discoveryAgent(new QBluetoothServiceDiscoveryAgent), serviceCount(0) {
    connect(m_discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)),
         this, SLOT(serviceDiscovered(QBluetoothServiceInfo)));
    connect(m_discoveryAgent, SIGNAL(finished()), this, SLOT(discoveryFinished()));
}

ServiceManager::~ServiceManager() {
}

void ServiceManager::serviceDiscovered(const QBluetoothServiceInfo &serviceInfo) {
     qDebug() << "Discovered service on"
              << serviceInfo.device().name() << serviceInfo.device().address().toString();
     qDebug() << "\tService name:" << serviceInfo.serviceName();
     qDebug() << "\tDescription:"
              << serviceInfo.attribute(QBluetoothServiceInfo::ServiceDescription).toString();
     qDebug() << "\tProvider:"
              << serviceInfo.attribute(QBluetoothServiceInfo::ServiceProvider).toString();
     qDebug() << "\tL2CAP protocol service multiplexer:"
              << serviceInfo.protocolServiceMultiplexer();
     qDebug() << "\tRFCOMM server channel:" << serviceInfo.serverChannel();

     serviceCount++;
     m_service = serviceInfo;
}

void ServiceManager::discoveryFinished() {
    qDebug() << "[ServiceManager] Device discovery finished!";

    if(serviceCount == 1) {
        qDebug() << "[ServiceManager] Single service instance found!";
        emit singleServiceInstance();
    } else {
        emit noServiceFound();
    }
}


void ServiceManager::startDiscovery() {
    startDiscovery(QBluetoothUuid(serviceUuid));
}

void ServiceManager::startDiscovery(const QtMobility::QBluetoothUuid &uuid) {
    if (m_discoveryAgent->isActive())
        m_discoveryAgent->stop();

    m_discoveryAgent->setUuidFilter(uuid);
    m_discoveryAgent->start();

    qDebug() << "[ServiceManager] Discovering services...";
}

void ServiceManager::stopDiscovery() {
    if(m_discoveryAgent){
        m_discoveryAgent->stop();
        qDebug() << "[ServiceManager] Service discovery stopped!";
    }
}

QtMobility::QBluetoothServiceInfo ServiceManager::service() const {
    return m_service;
}
